""" attempt to 
    simulates dbf table in csv file 

    Ponomarev S.A. ponomarevsa@yandex.ru 
"""

class csvtable:
    def __init__(self, TableName = 'Table1', columns = []):
        self.table = []
        self.TableName = TableName
        self.columns = columns
        self.index = -1
        self.key_index = -1
        self._no_filter_table = []

    def Filter(self, flag, field = 0, value = 0):
        if self._no_filter_table == []:
            self._no_filter_table.extend(self.table)

        if flag:
            field = self._get_col_index(field)
            self.table = []
            for r in self._no_filter_table:
                if r[field] == value:
                    self.table.append(r)
        else:
            self.table = []
            self.table.extend(self._no_filter_table)             
        self.index = 0 
    
    def Clear(self):
        self.table = []
        self.columns = []
        self.index = -1
        self.key_index = -1
        self._no_filter_table = []

    def _get_col_index(self, field):
        # Column, pos in rec list
        i = 0
        field_index = -1
        for c in self.columns:
            if c == field: field_index = i
            i += 1
        # If field not found
        if field_index == -1: return None
        return field_index
    def _get_next_key_value(self):
        id = 0
        for rec in self.table:
            if rec[self.key_index] == '': i = 0
            else: i = int(rec[self.key_index])
            if id < i: id = i
        id += 1
        return id 
    
    def setTable(self, data):
        self.Clear()
        self.columns = data[0]
        for n in range(1, len(data)):
            self.table.append(data[n])

    def getTable(self):
        data = []
        data.append(self.columns) 
        for n in range(0, len(self.table)):
            data.append(self.table[n]) 
        return data
        
    def LoadFromFile(self, FileName):
        self.Clear()
        data = open(FileName, 'r').read()
        data = data.split('\n')
        # Read column
        for col in data[0].split(';'):
            if col != '': self.columns.append(col)
        # Read recs
        for n in range(1, len(data) - 1):
            if data[n] != '':
                rec = []
                for field in range(0, len(self.columns)):
                    rec.append(data[n].split(';')[field]) 
            self.table.append(rec)  
        if len(self.table) >= 0: self.index = 0     
        
    def SaveToFile(self, FileName):
        out = ''
        for col in self.columns:
            out += col.replace(';', '.,') + ';'
        out += '\n'
        for rec in self.table:
            for field in rec:
                field = str(field)
                out += field.replace(';', '.,') + ';'
            out += '\n'
        open(FileName, 'w').write(out)
        
    def Print(self):
        print self.TableName
        print self.columns
        for r in self.table:
            print r
            
    def Insert(self):
        col_count = len(self.columns)
        rec = []
        [rec.append('') for i in range(0, col_count)]
        self.table.append(rec)
        self.index = self.RecCount() - 1 
        # Add key value
        if self.key_index != -1:
            self.table[self.index][self.key_index] = self._get_next_key_value()

    def setField(self, field, value):
        field_index = self._get_col_index(field)
        if field_index != None and field_index != self.key_index: 
            self.table[self.index][field_index] = value
    
    def getField(self, field):
        field_index = self._get_col_index(field)
        if field_index != None: 
            return unicode(self.table[self.index][field_index], 'cp1251')
            #return self.table[self.index][field_index]
        
    def Delete(self):
        self.table.remove(self.table[self.index])

    def First(self):
        #if self.index != -1:
        #    self.index = 0
        if len(self.table) >= 0:
            self.index = 0
    def Next(self):
        if self.index < self.RecCount(): 
            self.index += 1
    def Last(self):
        if self.index != -1: 
            self.index += self.RecCount() - 1
    def RecCount(self):
        return len(self.table)
    def setKey(self, field):
        self.key_index = self._get_col_index(field)
        

        
if __name__ == '__main__':
    tblRefer = csvtable()
    print 'start'
    tblRefer.LoadFromFile('income.csv')
    print tblRefer.RecCount() 




